package com.mlxg.master.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlxg.enmu.ExpoType;
import com.mlxg.master.domain.HzExhibitor;
import com.mlxg.master.mapper.HzExhibitorSourceMapper;
import com.mlxg.master.service.HzExhibitorSourceService;
import com.mlxg.selver.domain.ExUser;
import com.mlxg.selver.domain.ExUserAttach;
import com.mlxg.selver.domain.ExUserExpo;
import com.mlxg.selver.domain.IdMapping;
import com.mlxg.selver.service.IExUserAttachService;
import com.mlxg.selver.service.IExUserExpoService;
import com.mlxg.selver.service.IExUserService;
import com.mlxg.selver.service.IIdMappingService;
import com.mlxg.untils.BCryptUtils;
import com.mlxg.untils.oss.GeneralOSSUpLoadUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Select;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 展商 服务实现类
 * </p>
 *
 * @author zcy
 * @date 2025/5/23 9:50
 */
//@Slf4j
@Service
@DS("master")
public class HzExhibitorSourceServiceImpl extends ServiceImpl<HzExhibitorSourceMapper, HzExhibitor> implements HzExhibitorSourceService {
    private static final Logger logger = LoggerFactory.getLogger(HzExhibitorSourceServiceImpl.class);
    @Autowired
    private HzExhibitorSourceMapper hzExhibitorSourceMapper;

    @Autowired
    private IExUserService exUserService;

    @Autowired
    private IIdMappingService idMappingService;

    @Autowired
    private IExUserAttachService exUserAttachService;

    @Autowired
    private IExUserExpoService exUserExpoService;

    @Autowired
    private ModelMapper modelMapper;

    /**
     * 通用文件上传
     */
    @Autowired
    private GeneralOSSUpLoadUtils generalOSSUpLoadUtils;

    // 迁移服务代码示例
    @Override
    //@DSTransactional
    public void generateIdMapping() {
        int pageSize = 1000;
        int pageNum = 1;
        int totalProcessed = 0;
        int totalSuccess = 0;
        int totalFailed = 0;
        int totalPageFailed = 0;

        // 先获取所有最新记录的ID
        List<String> latestIds = hzExhibitorSourceMapper.selectLatestExhibitorIds();

        // 对ID列表分页处理
        while (!CollectionUtils.isEmpty(latestIds)) {
            int fromIndex = (pageNum - 1) * pageSize;
            if (fromIndex >= latestIds.size()) {
                break;
            }

            int toIndex = Math.min(fromIndex + pageSize, latestIds.size());
            List<String> pageIds = latestIds.subList(fromIndex, toIndex);

            try {
                QueryWrapper<HzExhibitor> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id", pageIds)
                        .orderByDesc("create_date")  // 与Mapper一致
                        .orderByDesc("id");          // 与Mapper一致

                List<HzExhibitor> hzExhibitors = hzExhibitorSourceMapper.selectList(queryWrapper);

                totalProcessed += hzExhibitors.size();
                logger.info("开始处理第 {} 页数据，当前页记录数: {}", pageNum, hzExhibitors.size());

                for (HzExhibitor oldUser : hzExhibitors) {
                    try {
                        processSingleRecord(oldUser);
                        totalSuccess++;
                    } catch (Exception e) {
                        totalFailed++;
                        logger.error("处理展商记录失败，旧展商ID: {}", oldUser.getId(), e);
                    }
                }

                pageNum++;
            } catch (Exception e) {
                totalPageFailed++;
                logger.error("处理第 {} 页数据时发生异常", pageNum, e);
                pageNum++;
            }
        }

        logger.info("数据迁移完成 - 总共处理页数: {}, 总记录数: {}, 成功: {}, 失败: {}, 分页处理失败: {}",
                pageNum - 1, totalProcessed, totalSuccess, totalFailed, totalPageFailed);
    }


    private void processSingleRecord(HzExhibitor oldUser) {
        // 展商信息保存
        ExUser newUser = getExUser(oldUser);

        // 创建映射关系
        IdMapping idMapping = new IdMapping();
        idMapping.setExHibitorId(oldUser.getId());
        idMapping.setUserId(newUser.getUserId());
        idMappingService.save(idMapping);

        // 保存参加过的展会
        if (!StringUtils.isEmpty(oldUser.getExpoRecords())) {
            createUserExpo(newUser, oldUser.getExpoRecords());
        }

        // 保存展商的公司信息
        createExUserAttach(oldUser, newUser);
    }

    /**
     * 创建展商信息
     *
     * @param oldUser
     * @return
     */
    public ExUser getExUser(HzExhibitor oldUser) {
        try {
            ExUser newUser = modelMapper.map(oldUser, ExUser.class);

            if (StringUtils.isBlank(newUser.getAccount())) {
                if (!StringUtils.isBlank(oldUser.getUserTel())) {
                    newUser.setAccount(oldUser.getUserTel());
                } else {
                    newUser.setAccount(null);
                }
            }
            //需要清空手机号和邮箱
            newUser.setUserPhone(null);
            newUser.setUserEmail(null);
            // 设置密码
            if (oldUser.getCause() != null) {
                newUser.setPassword(BCryptUtils.encryptionPassword(oldUser.getCause()));
            } else {
                newUser.setPassword(BCryptUtils.encryptionPassword("123456"));
            }
            //是否推荐
            if (oldUser.getColumn12() != null) {
                if (oldUser.getColumn12() == 0) {
                    newUser.setIsRecommend(1);
                } else {
                    newUser.setIsRecommend(0);
                }
            }
            newUser.setStatus(1);
            newUser.setDelFlag(1);
            // 保存新用户
            exUserService.save(newUser);
            return newUser;
        } catch (Exception e) {
            logger.error("创建新用户失败，旧展商ID: {}", oldUser.getId(), e);
            throw new RuntimeException("创建新用户失败", e);
        }
    }

    /**
     * 创建展商的公司信息
     */
    public void createExUserAttach(HzExhibitor oldUser, ExUser newUser) {
        try {
            ExUserAttach newExUserAttach = modelMapper.map(oldUser, ExUserAttach.class);
            newExUserAttach.setUserId(newUser.getUserId());

            // 验证URL字段
            //公司log中文
            newExUserAttach.setEnterpriseLogo(processUrlField(newExUserAttach.getEnterpriseLogo(), "companyLog"));

            newExUserAttach.setEnterpriseLogoEn(validateUrl(newExUserAttach.getEnterpriseLogoEn()));

            newExUserAttach.setCompanyWechatPublicNumberUrl(validateUrl(newExUserAttach.getCompanyWechatPublicNumberUrl()));

            newExUserAttach.setEnterprisePublicityVideoUrl(validateUrl(newExUserAttach.getEnterprisePublicityVideoUrl()));

            newExUserAttach.setVideoUrl(validateUrl(newExUserAttach.getVideoUrl()));

            exUserAttachService.save(newExUserAttach);
        } catch (Exception e) {
            logger.error("创建展商公司信息失败，新用户ID: {}", newUser.getUserId(), e);
            throw new RuntimeException("创建展商公司信息失败", e);
        }
    }

    /**
     * 验证URL是否以http开头
     */
    private String validateUrl(String url) {
        return (url != null && url.startsWith("http")) ? url : null;
    }


    /**
     * 处理URL字段，将相对路径转换为OSS地址
     */
    private String processUrlField(String fieldValue, String ossDir) {
        if (StringUtils.isBlank(fieldValue)) {
            return null;
        }
        if (fieldValue.startsWith("/")) {
            try {
                String url = generalOSSUpLoadUtils.uploadUrlToOss(fieldValue, ossDir);
                return url;
            } catch (IOException e) {
                return null;
            }
        } else if (fieldValue.startsWith("http://") || fieldValue.startsWith("https://")) {
            return fieldValue;
        }
        return null;
    }


    /**
     * 构造展商参加过的展会信息
     */
    public void createUserExpo(ExUser newUser, String expoRecords) {
        try {
            if (!StringUtils.isEmpty(expoRecords)) {
                List<ExUserExpo> exUserExpoList = new ArrayList<>();
                String[] expoIds = expoRecords.substring(1, expoRecords.length() - 1).split("\\|");

                for (String expoIdStr : expoIds) {
                    try {
                        Integer expoId = Integer.valueOf(expoIdStr);
                        ExUserExpo exUserExpo = new ExUserExpo();
                        exUserExpo.setExUserId(newUser.getUserId());
                        exUserExpo.setExpoId(ExpoType.getExpoIdById(expoId));
                        exUserExpoList.add(exUserExpo);
                    } catch (NumberFormatException e) {
                        logger.error("解析展会ID失败，无效的ID: {}, 用户ID: {}", expoIdStr, newUser.getUserId(), e);
                    } catch (Exception e) {
                        logger.error("创建展会记录失败，用户ID: {}, 展会ID字符串: {}",
                                newUser.getUserId(), expoIdStr, e);
                    }
                }

                if (!CollectionUtils.isEmpty(exUserExpoList)) {
                    exUserExpoService.saveBatch(exUserExpoList);
                }
            }
        } catch (Exception e) {
            logger.error("处理用户展会记录失败，用户ID: {}, 展会记录: {}",
                    newUser.getUserId(), expoRecords, e);
            throw new RuntimeException("处理用户展会记录失败", e);
        }
    }


}
